import 'dart:collection';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:opene/app_utils.dart';
import 'package:toast/toast.dart';

import '../app_constant.dart';
import '../app_theme.dart';
import '../net/network_manager.dart';
import '../net/response/base_response.dart';
import '../task_bean_entity.dart';

typedef ApiCallback = Future<Map<String, dynamic>> Function(
    int pageNum, int pageSize);
typedef CustomChildBuilder = Widget Function(
    BuildContext context, List<dynamic> dataList);

class TaskScreen extends StatefulWidget {
  final ApiCallback apiCallback; // API请求方法
  final Widget Function(BuildContext context, dynamic item)
      itemBuilder; // 每一项的构建
  final Widget emptyWidget; // 空数据时的展示组件
  final CustomChildBuilder childBuilder; // 自定义 child 构建方法

  const TaskScreen({
    Key key,
    this.apiCallback,
    this.itemBuilder,
    this.emptyWidget = const Center(child: Text("")),
    this.childBuilder,
  }) : super(key: key);

  @override
  TaskScreenState createState() => TaskScreenState();
}

class TaskScreenState extends State<TaskScreen>  with SingleTickerProviderStateMixin {
  TabController _tabController;
  int type = 0;
  String url = Constants.searchTaskList;
  int pageNum = 1; // 当前页数
  final int pageSize = 10; // 每页大小
  int totalPages = 1; // 总页数
  bool isLoading = false; // 是否正在加载
  List<TaskBeanEntity> dataList = []; // 数据列表
  // 创建EasyRefreshController
  EasyRefreshController _controller = EasyRefreshController();

  Future<void> fetchData({bool isRefresh = false}) async {
    if (isLoading) return; // 防止重复加载
    setState(() {
      isLoading = true;
    });

    Map<String, dynamic> map = new HashMap();
    map['index'] = pageNum;
    map['limit'] = pageSize;

    BaseResponse baseResponse =
        await NetworkManager().request(context,url, params: map);
    print(baseResponse.status);
    isLoading = false;
    if (baseResponse.status == 200) {
      TaskBean loginData = TaskBean.fromJson(baseResponse.data);
      List<TaskBeanEntity> newData = loginData.results;

      try {
        setState(() {
          if (isRefresh) {
            dataList = newData;
          } else {
            dataList.addAll(newData);
          }
          totalPages = int.parse(loginData.totalPage) ?? 1; // 设置总页数
        });
      } catch (e) {
        debugPrint("加载数据失败: $e");
      } finally {
        setState(() {
          isLoading = false;
        });
      }
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg),duration: Toast.lengthShort, gravity: Toast.bottom);
    }

    _controller.finishRefresh();

    ///这里noMore=true 已到最后一页
    _controller.finishLoad(noMore: pageNum >= totalPages);


  }

  Future<void> onRefresh() async {
    dataList.clear();
    setState(() {
      pageNum = 1;
    });
    await fetchData(isRefresh: true);
  }

  Future<void> onLoad() async {
    if (pageNum >= totalPages) return;
    setState(() {
      pageNum++;
    });
    await fetchData();
  }

  @override
  void initState() {
    super.initState();
    // onRefresh();
    _tabController = TabController(length: 2, vsync: this);
    _tabController.animation.addListener(_handleTabAnimation);
  }

  void _handleTabAnimation() {
    print('Current Tab Index: ${_tabController.animation.value}');
    if(type == _tabController.animation.value){
      return;
    }

    if(_tabController.animation.value==0){
      type = 0;
      print('searchTaskList');
      url = Constants.searchTaskList;
      onRefresh();
      return;
    }
    if(_tabController.animation.value==1){
      type = 1;
      print('searchDoneTaskList');
      url = Constants.searchDoneTaskList;
      onRefresh();
      return;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: PreferredSize(
        preferredSize: const Size.fromHeight(40),
        child: AppBar(
          backgroundColor: Colors.white,
          elevation: 1, //阴影
          title: SizedBox(
            height: 30,
            child: TabBar(
              // isScrollable: true,
              //导航栏及页面是否可以滚动
              indicatorColor: MyAppTheme.nearlyBlue,
              labelColor: MyAppTheme.nearlyBlue,
              unselectedLabelColor: Colors.black,
              labelStyle: MyAppTheme.title,
              unselectedLabelStyle: MyAppTheme.title,
              controller: _tabController,
              tabs: const [
                Tab(child: Text("Pending")),
                Tab(child: Text("Done")),
              ],
            ),
          ),
        ),
      ),
      body:EasyRefresh(
        firstRefresh: true,
        enableControlFinishRefresh: true,
        // enableControlFinishLoad: true,
        header: BallPulseHeader(
          backgroundColor: Colors.white,
          color: MyAppTheme.nearlyBlue,
          // enableInfiniteRefresh: true
        ),
        footer: BallPulseFooter(
          backgroundColor: Colors.white,
          color:MyAppTheme.nearlyBlue,
        ),
        onRefresh: onRefresh,
        onLoad: onLoad,
        controller: _controller,
        child: widget.childBuilder != null
            ? widget.childBuilder(context, dataList)
            : (dataList.isEmpty
            ? widget.emptyWidget
            : ListView.builder(
          itemCount: dataList.length,
          itemBuilder: (context, index) {
            TaskBeanEntity taskBean = dataList[index];
            return Column(
              children: [
                ListTile(
                    contentPadding: EdgeInsets.only(left: 10.0,right: 10.0,top:(index==0)?10:0 ),
                    onTap: (){
                      print(index);
                    },
                    subtitle: Row(
                      children: [
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.end,
                          children: [
                            Visibility(
                              visible: true,
                              child: Text("Time: ", style: MyAppTheme.hint),
                            ),
                            Visibility(
                              visible: true,
                              child: Text("Task  Type: ", style: MyAppTheme.hint),
                            ),
                            Visibility(
                              visible: taskBean.containerNo==null?false:true,
                              child: Text("Container: ", style: MyAppTheme.hint),
                            ),
                            Visibility(
                              visible: taskBean.sku==null?false:true,
                              child: Text("SKU: ", style: MyAppTheme.hint),
                            ),
                            Visibility(
                              visible: taskBean.location==null?false:true,
                              child: Text("Location: ", style: MyAppTheme.hint),
                            ),
                            Visibility(
                              visible: taskBean.trackingNumber==null?false:true,
                              child: Text("Tracking: ", style: MyAppTheme.hint),
                            ),
                            Visibility(
                              visible: taskBean.batchNo==null?false:true,
                              child: Text("Batch: ", style: MyAppTheme.hint),
                            ),
                            Visibility(
                              visible: taskBean.ibLpn==null?false:true,
                              child: Text("IBLPN: ", style: MyAppTheme.hint),
                            ),
                            Visibility(
                              visible: taskBean.uniqId==null?false:true,
                              child: Text("Uniq ID: ", style: MyAppTheme.hint),
                            ),
                          ],
                        ),
                        Expanded(
                          // 这个Expanded小部件会占据所有可用空间
                          child: Container(
                            margin: const EdgeInsets.all(0),
                            padding: const EdgeInsets.all(0),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Visibility(
                                  visible: true,
                                  child: Text(Utils.getStringisEmpty(taskBean.updatedDatetime), maxLines: 1,style: MyAppTheme.text),
                                ),
                                Visibility(
                                  visible: true,
                                  child: Text(Utils.getStringisEmpty(taskBean.taskType), maxLines: 1,style: MyAppTheme.text),
                                ),
                                Visibility(
                                  visible: taskBean.containerNo==null?false:true,
                                  child: Text(Utils.getStringisEmpty(taskBean.containerNo),maxLines: 1, style: MyAppTheme.text),
                                ),
                                Visibility(
                                  visible: taskBean.sku==null?false:true,
                                  child: Text(Utils.getStringisEmpty(taskBean.sku),maxLines: 1, style: MyAppTheme.text),
                                ),
                                Visibility(
                                  visible: taskBean.location==null?false:true,
                                  child: Text(Utils.getStringisEmpty(taskBean.location),maxLines: 1, style: MyAppTheme.text),
                                ),
                                Visibility(
                                  visible: taskBean.trackingNumber==null?false:true,
                                  child: Text(Utils.getStringisEmpty(taskBean.trackingNumber),maxLines: 1, style: MyAppTheme.text),
                                ),
                                Visibility(
                                  visible: taskBean.batchNo==null?false:true,
                                  child: Text(Utils.getStringisEmpty(taskBean.batchNo),maxLines: 1, style: MyAppTheme.text),
                                ),
                                Visibility(
                                  visible: taskBean.ibLpn==null?false:true,
                                  child: Text(Utils.getStringisEmpty(taskBean.ibLpn),maxLines: 1, style: MyAppTheme.text),
                                ),
                                Visibility(
                                  visible: taskBean.uniqId==null?false:true,
                                  child: Text(Utils.getStringisEmpty(taskBean.uniqId),maxLines: 1, style: MyAppTheme.text),
                                ),
                              ],
                            ),
                          ),
                        ),
                        Visibility(
                          visible: type==1?false:true,
                          child:  Icon(
                            Icons.arrow_forward_ios,
                            size: 15,
                          ),
                        ),
                      ],
                    )),
                Divider(),
              ],
            );
          },
        )),
      ),
    );
  }
}

class TaskBean {
  String index;
  String limit;
  String total;
  String totalPage;
  // List<dynamic> results;

  List<TaskBeanEntity> results;

  TaskBean(this.index, this.limit, this.total, this.totalPage, this.results);

  TaskBean.fromJson(Map<dynamic, dynamic> json)
      : index = json['index'] as String,
        limit = json['limit'] as String,
        total = json['total'] as String,
        totalPage = json['totalPage'] as String,
        results = new List<dynamic>.from(json['results']).map((userJson) => TaskBeanEntity.fromJson(userJson)).toList();
}
